<template>
  <div class="workspacecc" style="height: 100%">
    <el-container
      ref="listWarp"
      style="height: 100%; background-color: #fff"
      v-loading="addLoading"
    >
      <!-- <el-header class="toolbar-wap" style="height:45px">头部按钮</el-header> -->
      <el-main class="page-main" style="height: 100%">
        <div class="content" style="width: 650px; margin: 0 auto">
          <el-form
            :model="form"
            :rules="rules"
            class="demo-ruleForm"
            label-width="100px"
            ref="form"
          >
            <el-form-item label="服务类型" prop="serverType">
              <el-radio-group size="small" v-model="form.serverType">
                <el-radio-button label="0">投诉</el-radio-button>
                <el-radio-button class="left" label="1">建议</el-radio-button>
                <el-radio-button class="left" label="2">咨询</el-radio-button>
                <el-radio-button class="left" label="3">表扬</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系人" prop="postUserName">
              <el-input
                v-model="form.postUserName"
                placeholder="请输入联系人"
                maxlength="15"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
              ></el-input>
            </el-form-item>
            <el-form-item label="服务范围" prop="serviceScopeName">
              <el-cascader
                placeholder="请选择服务范围"
                style="width: 550px"
                ref="cascaderAddr"
                :options="options"
                :props="proppp"
                @change="getValue"
                v-model="form.serviceScopeName"
              />
            </el-form-item>
            <el-form-item label="服务单位">
              <el-input
                type="textarea"
                placeholder="服务单位根据您选择的服务范围自动解析判断得出"
                v-model="unitInfo"
                readonly
              ></el-input>
            </el-form-item>
            <el-form-item label="发帖标题" prop="postTitle">
              <el-input
                v-model="form.postTitle"
                maxlength="50"
                placeholder="请输入发帖标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="详细描述" prop="content">
              <el-input
                type="textarea"
                maxlength="250"
                v-model="form.content"
                placeholder="请输入详细描述"
              ></el-input>
            </el-form-item>
            <el-form-item label="是否公开" prop="ifShielding">
              <el-radio-group v-model="form.ifShielding">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-row>
              <el-form-item label="图片：">
                <div style="color: #999999">（最多上传4张）</div>
                <div class="img_box">
                  <el-upload
                    :class="{ show: uploadDisabled && imgUrl.length > 3 }"
                    action="/api/file/upload"
                    list-type="picture-card"
                    :data="Imgdata"
                    :headers="headers"
                    accept="image/*"
                    :on-preview="handlePreview"
                    :before-upload="beforeAvatarUpload"
                    :on-remove="handleRemove"
                    :on-success="handleAvatarSuccess"
                    :on-progress="onProgresspc"
                    :before-remove="beforeRemove"
                    multiple
                    :limit="6"
                    :on-exceed="handleExceed"
                    :file-list="fileList"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </el-form-item>
            </el-row>
          </el-form>
          <div
            class="dialog-footer"
            style="margin-top: 80px; background: #fff; border-top: none"
          >
            <el-button @click="cencal">取 消</el-button>
            <el-button @click="addBtn('form')" type="primary">确定</el-button>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { catalogueApi } from "@/api/services/catalogue";
import Token from "@/itsoftUI/auth/token.js";
import { validateEmail, validateMobile } from "@/itsoftUI/utils/validate";
import { compression } from "@/itsoftUI/utils/imgCompression";
export default {
  components: {},
  data() {
    return {
      options: [],
      addLoading: false,
      unitInfo: "",
      Imgdata: {
        system: "service",
      },
      headers: {
        Token: "",
        TokenKey: "",
      },
      uploadDisabled: true,
      fileList: [],
      imgUrl: [],
      form: {
        ifShielding: "0",
        serverType: "0",
        content: "",
        id: "",
        images: "",
        phone: "",
        postTitle: "",
        postUserId: "",
        postUserName: "",
        serviceScopeId: "",
        serviceScopeName: "",
        source: "",
        SelectCloumnName: [],
      },
      proppp: {
        children: "children",
        value: "id",
        label: "name",
      },
      deptFlag: true,
      rules: {
        serverType: [
          {
            required: true,
            message: "请至少选择一个服务类型",
            trigger: "change",
          },
        ],
        postUserName: [
          { required: true, message: "请填写联系人", trigger: "change" },
        ],
        phone: [{ required: true, validator: validateMobile }],
        serviceScopeName: [
          {
            required: true,
            message: "请至少选择一个服务范围",
            trigger: "change",
          },
        ],
        postTitle: [
          { required: true, message: "请填写发帖标题", trigger: "change" },
        ],
        content: [
          { required: true, message: "请填写描述信息", trigger: "change" },
        ],
        ifPublish: [
          { required: true, message: "请选择是否公开", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.GetScope();
    this.form.serverType = this.$route.query.type;
  },
  updated() {},
  methods: {
    handlePreview(e) {
      window.open(e.url, "_blank");
    },
    beforeAvatarUpload(file) {
      this.headers.Token = Token.getToken();
      this.headers.TokenKey = Token.getTokenKey();
      let _this = this;
      return new Promise((resolve, reject) => {
        let image = new Image(),
          resultBlob = "";
        image.src = URL.createObjectURL(file);
        image.onload = () => {
          // 调用方法获取blob格式，方法写在下边
          resultBlob = compression(image, file);
          console.log(resultBlob);
          resolve(resultBlob);
        };
        image.onerror = () => {
          reject();
        };
      });
    },
    handleAvatarSuccess(file, fileList) {
      //图片上传成功
      this.uploadDisabled = true;
      this.imgUrl.push(file.data.path);
    },
    handleRemove(file, fileList) {
      this.uploadDisabled = false;
      if (file.response) {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i] == file.response.data.path) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].url == file.url) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      }
      if (file.response) {
        for (var i = 0; i < this.imgUrl.length; i++) {
          if (this.imgUrl[i] == file.response.data.path) {
            this.imgUrl.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.imgUrl.length; i++) {
          if (file.url.indexOf(this.imgUrl[i]) != -1) {
            this.imgUrl.splice(i, 1);
            break;
          }
        }
      }
    },
    onProgresspc() {
      this.uploadDisabled = true;
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        // `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
        //   files.length + fileList.length
        // } 个文件`
        "当前限制选择6个文件，超出选择范围"
      );
    },
    cencal() {
      this.$refs.form.clearValidate();
      this.$refs.form.resetFields();
      this.unitInfo = "";
      this.$router.push("home");
    },
    getValue(v) {
      this.SelectCloumnName = this.$refs[
        "cascaderAddr"
      ].getCheckedNodes()[0].pathLabels;

      let serviceScope = v;
      this.form.serviceScopeId = serviceScope[serviceScope.length - 1];

      this.unitInfo = "";
      let typeName = 1;
      this.addLoading = true;
      catalogueApi
        .scopeUsersList(this.form.serviceScopeId, typeName)
        .then((res) => {
          if (res.errorCode === 0) {
            this.addLoading = false;
            if (res.data.userList.length == 0) {
              this.$message.error("请联系管理员设置受理人");
              this.deptFlag = false;
              return false;
            }
            if (res.data !== "{}") {
              this.deptFlag = true;
              this.unitInfo = "服务单位【" + res.data.deptName + "】,受理人";
              res.data.userList.forEach((re) => {
                this.unitInfo += "【" + re.userName + "】,";
              });
              this.unitInfo = this.unitInfo.substr(0, this.unitInfo.length - 1);
            } else {
              this.unitInfo = "暂未受理单位";
            }
          }
        });
    },

    // 获取服务范围下拉
    GetScope() {
      let isShowNoDept = "0";
      catalogueApi.GetScopeTree(isShowNoDept).then((res) => {
        if (res.status == "success") {
          this.options = res.data;
        }
      });
    },
    addBtn(form) {
      // if (this.SelectCloumnName==undefined) {
      //    this.$message.error("请服务范围下面的服务单位");
      //   return false;
      // }
      console.log(this.SelectCloumnName);
      if (this.SelectCloumnName) {
        this.form.serviceScopeName = this.SelectCloumnName[
          this.SelectCloumnName.length - 1
        ];
      }

      if (!this.deptFlag) {
        this.$message.error("请联系管理员设置受理人");
        return false;
      }
      this.form.ifRecord = 0;
      this.form.source = "pc";
      this.form.images = this.imgUrl.join(",");
      this.addLoading = true;
      this.$refs[form].validate((valid) => {
        if (valid) {
          catalogueApi.save(this.form).then((res) => {
            if (res.status == "success") {
              this.$message.success("提交成功");
              this.addLoading = false;
              // this.addLoading = false;
              this.unitInfo = "";
              this.$refs.form.clearValidate();
              this.$refs.form.resetFields();
              this.$router.push("home");
            }
          });
        } else {
          this.addLoading = false;
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.workspacecc {
  .el-radio-button {
    margin-right: 30px;
  }
  .left {
    border-left: 1px solid #dcdfe6;
  }
  ::v-deep .show .el-upload--picture-card {
    display: none !important;
  }
}
</style>
